from decimal import Decimal

from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response

from goods.models import SKU
from orders.serializers import OrderSettlementSerializer, CommitOrderSerializer


class OrderSettlementView(APIView):
    """去结算"""

    permission_classes = [IsAuthenticated]

    def __init__(self):
        super().__init__()
        self.redis_conn = get_redis_connection('cart')

    def get(self, request):

        # 获取redis中的hash和几个两个数据
        user = request.user
        # 把hash中那些勾选的商品的sku_id取出来包装到一个新字典中
        cart_redis_dict = self.redis_conn.hgetall('cart_%s' % user.id)
        selected_ids = self.redis_conn.smembers('selected_%s' % user.id)
        # 把勾选商品的sku模型再获取出来
        cart_dict = {}
        for sku_id_bytes in selected_ids:
            cart_dict[int(sku_id_bytes)] = int(cart_redis_dict[sku_id_bytes])
        # 遍历sku 查询集取出一个一个的sku模型
        skus = SKU.objects.filter(id__in=cart_dict.keys())
        # 给每个sku模型多定义一个count属性
        print(cart_dict)
        for sku in skus:
            sku.count = cart_dict[sku.id]

        # 定义一个运费
        freight = Decimal('10.00')
        # 序列化的数据为 {'freight': 10, 'skus': skus}
        data_dict = {'freight': freight, 'skus': skus}
        serializer = OrderSettlementSerializer(instance=data_dict)
        return Response(serializer.data)


class CommitOrderView(CreateAPIView):
    """保存订单"""

    permission_classes = [IsAuthenticated]

    serializer_class = CommitOrderSerializer
